package com.tuonbed.qrqd;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 生成图片
 */
public class QRCodeMaker {

    private static final int PIC_WIDTH = PROPARAM.SIZE;
    private static final int PIC_HEIGHT = PROPARAM.SIZE;
    private static final int QR_SIZE = PROPARAM.SIZE;


    private static final int BLUE = 0xFF3ED547;
    private static final int WHITE = 0xFFFFFFFF;
    private static final int BLACK = 0xFF000000;
    private static final int RED = 0xFFFF0000;

    private static final String IMG_FORMATE = "jpg";



    private static final int LOGO_BORDER_WIDTH = 2;//LOGO边框宽度
    private static final Color LOGO_BORDER_COLOR = Color.WHITE;//LOGO边框颜色

    // TODO:logo file path


    /**
     * 生成二维码图片
     * @param info  二维码信息
     * @param out  目的图片地址
     */
    public static void MakeQRCode(String info, String out) throws WriterException, IOException {
        File outFile = new File(out);

        if (!outFile.getParentFile().exists()) {
            outFile.getParentFile().mkdirs();
        }

        BufferedImage image = toBufferedImg(getBitMatrix(info));

        ImageIO.write(image, IMG_FORMATE, outFile);

    }

    /**
     * 生成带logo的二维码图片
     * @param info      图片信息
     * @param out       输出图片地址
     * @param logoPath  logo图片地址
     * @throws WriterException
     * @throws IOException
     */
    public static void MakeQrCodeWithLogo(String info, String out, String logoPath) throws WriterException, IOException {
        File outFile = new File(out);

        if (!outFile.getParentFile().exists()) {
            outFile.getParentFile().mkdirs();
        }


        BufferedImage image = toTopAndButtonImg(getBitMatrix(info),true,info,PROPARAM.TITLE);


        if(PROPARAM.LOGO_PATH!=null){
            addLogo2QrCode(image, new File(PROPARAM.LOGO_PATH));
        }


        ImageIO.write(image, IMG_FORMATE, outFile);
    }


    /**
     * get bitMatrix from content
     * @param conten    qr_code info
     * @return
     * @throws WriterException
     */
    private static BitMatrix getBitMatrix(String conten) throws WriterException {
        MultiFormatWriter writer = new MultiFormatWriter();

        Map hint = new HashMap();
        hint.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        hint.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hint.put(EncodeHintType.MARGIN, 1);
        return writer.encode(conten, BarcodeFormat.QR_CODE, PIC_WIDTH, PIC_HEIGHT, hint);
    }

    private static BufferedImage toBufferedImg(BitMatrix bitMatrix) {
        int width = bitMatrix.getWidth();
        int height = bitMatrix.getHeight();

        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, bitMatrix.get(x, y) ? BLUE : WHITE);
            }
        }

        return image;
    }

    private static BufferedImage toTopAndButtonImg(BitMatrix bitMatrix,boolean isButtonDes,String info,String topMsg) {
        //info="编号："+info;

        int width = bitMatrix.getWidth();
        int height = bitMatrix.getHeight();
        BufferedImage image = new BufferedImage(width,isButtonDes?height+60:height, BufferedImage.TYPE_INT_RGB);

        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y+30, bitMatrix.get(x, y) ? BLACK : WHITE);
            }
        }

        Graphics2D graph = image.createGraphics();


        //标题
        BufferedImage textImage2 = FontImage.getImage(topMsg,new Font("宋体",Font.BOLD,jssize(topMsg)), QR_SIZE, 30);
        int width3 = textImage2.getWidth(null);
        int height3 = textImage2.getHeight(null);
        Image src2 =textImage2;
        graph.drawImage(src2, 0, 0, width3, height3, null);
        //结尾
        BufferedImage textImage = FontImage.getImage(info, QR_SIZE, 30);
        int width2 = textImage.getWidth(null);
        int height2 = textImage.getHeight(null);
        Image src =textImage;
        graph.drawImage(src, 0, QR_SIZE+30, width2, height2, null);
        graph.dispose();
        return image;
    }

    private static void addLogo2QrCode(BufferedImage qrImage, File logoFile) throws IOException {

        if (qrImage == null) {
            throw new RuntimeException("qrpic is null");
        }

        if (!logoFile.exists()) {
            throw new FileNotFoundException("can not found logo file at " + logoFile.getAbsolutePath());
        }

        BufferedImage logo = ImageIO.read(logoFile);

        int logoWidth = logo.getWidth(null);
        int logoHeight = logo.getHeight(null);

        if(qrImage.getWidth()/5<logoWidth){
            logoWidth=qrImage.getWidth()/5;
            logoHeight=qrImage.getHeight()*logoWidth/qrImage.getWidth();
        }

        // get logo position
        int x = (qrImage.getWidth() - logoWidth) / 2;
        int y = (qrImage.getHeight() - logoHeight) / 2;

        // draw logo on qr picture
        Graphics2D graphics2D = qrImage.createGraphics();

        graphics2D.drawImage(logo, x, y, logoWidth, logoHeight, null);
        graphics2D.drawRoundRect(x, y, logoWidth, logoHeight, 6, 6);

        graphics2D.setStroke(new BasicStroke(LOGO_BORDER_WIDTH));
        graphics2D.setColor(LOGO_BORDER_COLOR);
        graphics2D.drawRect(x, y, logoWidth, logoHeight);

        graphics2D.dispose();
    }

    private static int jssize(String context){
        int length = context.length();
        return QR_SIZE/length-1;
    }

}
